import hashlib

import sqlalchemy


def read_from_file(file_path):
    with open(file_path, 'r') as file:
        return file.read().strip()


APPID = read_from_file('./api/utils/openid/appid.txt')
SECRET = read_from_file('./api/utils/openid/secret.txt')

import requests


def set_openid_from_wechat(uid, code, engine):
    url = f"https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={code}&grant_type=authorization_code"
    response = requests.get(url)
    if response.status_code == 200:
        # print(response.json(), url)
        conn = engine.connect()
        try:
            openid = response.json().get('openid')
            openid_md5 = hashlib.md5(openid.encode('utf-8')).hexdigest()
            result = conn.execute(sqlalchemy.text("""
                    UPDATE user_auth SET open_id = :open_id WHERE uid = :uid
                """),
                                  {"uid": uid, "open_id": openid_md5})
            conn.commit()
            return result
        except Exception as e:
            raise e
        finally:
            conn.close()
    else:
        raise Exception(f"Failed to get openid: {response.text}")
